package com.fly.control;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.fly.conn.DBConnect;
import com.fly.model.Buyer;

public class BuyerControl {
	public static boolean insertBuyer(Buyer b){
		String sql = "insert into parambuyer(name, address, telephone, remark) values (?, ?, ?, ?)";
		DBConnect dbc = new DBConnect();
		dbc.prepareStatement(sql);
		try{
			int i=1;
			dbc.setString(i++, b.getName());
			dbc.setString(i++, b.getAddress());
			dbc.setString(i++, b.getTelephone());
			dbc.setString(i++, b.getRemark());
			dbc.executeUpdate();
			return true;
		} catch(Exception e){
			e.printStackTrace();
			System.out.println("insertBuyer ERROR");
		} finally{
			dbc.close();
		} 
		return false;
	}
	public static boolean deleteBuyer(int id){
		String sql = "delete * from parambuyer where id =" + id;
		DBConnect dbc = new DBConnect();
		dbc.prepareStatement(sql);
		try{
			dbc.executeUpdate();
			return true;
		} catch(Exception e){
			e.printStackTrace();
			System.out.println("deleteBuyer ERROR");
		} finally{
			dbc.close();
		}
		return false;
	}
	public static boolean updateBuyer(Buyer b, int id){
		String sql = "update parambuyer set name=?, address=?, telephone=?, remark=? where id =" + id;
		DBConnect dbc = new DBConnect();
		dbc.prepareStatement(sql);
		try{
			int i=1;
			dbc.setString(i++, b.getName());
			dbc.setString(i++, b.getAddress());
			dbc.setString(i++, b.getTelephone());
			dbc.setString(i++, b.getRemark());
			dbc.executeUpdate();
			return true;
		} catch(Exception e){
			e.printStackTrace();
			System.out.println("updateBuyer ERROR");
		} finally{
			dbc.close();
		}
		return false;
	}
	public static List<Buyer> getBuyerByName(String name){
		String sql = "select * from prambuyer where name like '%" + name + "%'";
		DBConnect dbc = new DBConnect();
		dbc.prepareStatement(sql);
		ResultSet rs = null;
		List<Buyer> list = new ArrayList<Buyer>();
		try{
			rs = dbc.executeQuery();
			while(rs.next()){
				Buyer b = new Buyer();
				b.setName(rs.getString("name"));
				b.setAddress(rs.getString("addrsee"));
				b.setTelephone(rs.getString("telephone"));
				b.setRemark(rs.getString("remark"));
				list.add(b);
			}
			return list;
		} catch(Exception e){
			e.printStackTrace();
			System.out.println("getBuyerByName ERROR");
		} finally{
			dbc.close();
		}
		return null;
	}
}
